#include <QtCore>
#include <QtNetwork>

#include <stdlib.h>

#include "bonjourserver.h"
#include "bonjourserviceregister.h"


BonjourServer::BonjourServer(QObject *parent) : QTcpServer(parent)
{
	bonjourRegister = new BonjourServiceRegister(this);

	// Attemtp to start server and listen (jeez, it's easier than it is in java...
	if (!listen())
		qDebug("Couldn't start server.");

	else
	{
		qDebug("Server started.");
		qDebug(QString::number(serverPort()).toStdString().c_str());

		connect(this, SIGNAL(newConnection()), this, SLOT(sendInfo()));

		// Register service with a title from this IP of type _weaveedit._tcp at this port.
		bonjourRegister->registerService(BonjourRecord(tr("%1\n%2")
							       .arg(QHostInfo::localHostName() + " running Ubuntu",
								    QString::number(serverPort())),
							       QLatin1String("_weaveedit._tcp"), QString()),
						 serverPort());
	}
}

/** Client tried to get our info. */
void BonjourServer::sendInfo()
{
	// Get client.
	QTcpSocket *clientConnection = nextPendingConnection();

	// Setup auto cleaning up of socket.
	connect(clientConnection, SIGNAL(disconnected()), clientConnection,
		SLOT(deleteLater()));

	// Send info back to client and disconnect.
	clientConnection->write(QString("This is where we put the IP, port of WeaveEdit server.").toAscii());
	clientConnection->disconnectFromHost();
}
